import { defineStore } from 'pinia'
const APP_KEY = import.meta.env.VITE_APP_TITLE
interface setSoreKey {
  name: string
  key: any
  value: any
}
export const usePermissionStore = defineStore('permission', {
  state: () => ({
    PERMISSION_MAP: {
      userLocation: {
        title: '地理位置',
        androidPermissionID: ['android.permission.ACCESS_FINE_LOCATION'],
        desc: `“${APP_KEY}”需要获取您的地理位置，用于计算统计距离等功能。`,
      },
      writePhotosAlbum: {
        title: '存储空间/相册权限', // 获取手机文件
        androidPermissionID: ['android.permission.WRITE_EXTERNAL_STORAGE'],
        desc: `“${APP_KEY}”需要读写设备上的照片及文件，用于读写/写入图片、文件等功能`,
      },
      camera: {
        title: '相机权限',
        androidPermissionID: ['android.permission.CAMERA'],
        desc: `“${APP_KEY}”需要访问您的相机，用于拍摄图片、视频、个性化头像等功能。`,
      },
      callPhone: {
        title: '拨打电话',
        androidPermissionID: ['android.permission.CALL_PHONE'],
        desc: `“${APP_KEY}”需要拨打电话权限，方便你快速拨打电话。`,
      },
    },
    isIos: plus.os.name === 'iOS',
    premission: {},
    viewObj: null,
  }),
  actions: {
    /**
     * 统一修改state某个key数据
     * @param {Object} payload -name>要修改的属性 key>要修改的字段 value>要修改的数据
     */
    $setStoreKey(payload: setSoreKey) {
      this[payload.name][payload.key] = payload.value
    },
    async requestPermissions(permissionID: string | number) {
      if (!this.premission[permissionID] && !this.isIos) {
        const viewObj = this.nativeObjView(permissionID)
        this.viewObj = viewObj
        viewObj.show()
      }
      // eslint-disable-next-line no-async-promise-executor
      return new Promise(async (resolve, reject) => {
        const res = await this.checkAuth(permissionID)
        resolve(res)
      })
    },
    // 权限检测
    async checkAuth(permissionID: any) {
      let result = 0
      switch (permissionID) {
        case 'userLocation': // 定位权限
          result = this.isIos
            ? this.iosLocationAuth()
            : ((await this.androidAuth(permissionID)) as number)
          break
        case 'writePhotosAlbum': // 相册权限
          result = this.isIos
            ? this.iosPhotoAuth()
            : ((await this.androidAuth(permissionID)) as number)
          break
        case 'camera': // 摄像头权限
          result = this.isIos
            ? this.iosCameraAuth()
            : ((await this.androidAuth(permissionID)) as number)
          break
        case 'callPhone': // 拨打电话
          result = this.isIos
            ? this.iosCameraAuth()
            : ((await this.androidAuth(permissionID)) as number)
          break
        default:
          result = 0
          break
      }
      return Promise.resolve(result)
    },
    // Android权限查询
    androidAuth(permissionVal: string | number) {
      const permissionID = this.PERMISSION_MAP[permissionVal].androidPermissionID
      // eslint-disable-next-line @typescript-eslint/no-this-alias
      const that = this
      return new Promise((resolve, reject) => {
        plus.android.requestPermissions(
          [...permissionID], // 理论上支持多个权限同时查询，但实际上本函数封装只处理了一个权限的情况。有需要的可自行扩展封装
          function (resultObj) {
            let result = 0
            for (let i = 0; i < resultObj.granted.length; i++) {
              const grantedPermission = resultObj.granted[i]
              console.log('已获取的权限：' + grantedPermission)
              result = 1
            }
            for (let i = 0; i < resultObj.deniedPresent.length; i++) {
              const deniedPresentPermission = resultObj.deniedPresent[i]
              console.log('拒绝本次申请的权限：' + deniedPresentPermission)
              result = 0
            }
            for (let i = 0; i < resultObj.deniedAlways.length; i++) {
              const deniedAlwaysPermission = resultObj.deniedAlways[i]
              console.log('永久拒绝申请的权限：' + deniedAlwaysPermission)
              result = -1
            }

            if (result === 1) {
              // '已获得授权'
              that.$setStoreKey({
                name: 'premission',
                key: permissionVal,
                value: true,
              })
            } else if (result === 0) {
              // '未获得授权'
              that.$setStoreKey({
                name: 'premission',
                key: permissionVal,
                value: false,
              })
            } else {
              that.$setStoreKey({
                name: 'premission',
                key: permissionVal,
                value: false,
              })
              that.gotoAppSetting()
            }
            resolve(result)
            if (that.viewObj) that.viewObj.close()
          },
          function (error) {
            console.log('申请权限错误：' + error.code + ' = ' + error.message)
            resolve({
              code: error.code,
              message: error.message,
            })
          },
        )
      })
    },
    // 跳转到**应用**的权限页面
    gotoAppSetting() {
      uni.showModal({
        title: '设置权限',
        content: `操作权限已被拒绝，请手动前往设置`,
        confirmText: '去设置',
        success: (res) => {
          if (res.confirm) {
            if (this.isIos) {
              const UIApplication = plus.ios.importClass('UIApplication')
              const application2 = UIApplication.sharedApplication()
              const NSURL2 = plus.ios.importClass('NSURL')
              const setting2 = NSURL2.URLWithString('app-settings:')
              application2.openURL(setting2)
              plus.ios.deleteObject(setting2)
              plus.ios.deleteObject(NSURL2)
              plus.ios.deleteObject(application2)
            } else {
              const Intent = plus.android.importClass('android.content.Intent')
              const Settings = plus.android.importClass('android.provider.Settings')
              const Uri = plus.android.importClass('android.net.Uri')
              const mainActivity = plus.android.runtimeMainActivity()

              // @ts-expect-error: 可正常执行
              const intent = new Intent()
              // @ts-expect-error: 存在的
              intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
              // @ts-expect-error: 存在的
              const uri = Uri.fromParts('package', mainActivity.getPackageName(), null)
              intent.setData(uri)
              // @ts-expect-error: 存在的
              mainActivity.startActivity(intent)
            }
          }
        },
        fail: () => {
          console.log(`%cuni.showModal失败：`, 'color:green;background:yellow')
        },
      })
    },
    // 定位是否开启
    iosLocationAuth() {
      let result = 0
      const cllocationManger = plus.ios.importClass('CLLocationManager')
      const enable = cllocationManger.locationServicesEnabled()
      const status = cllocationManger.authorizationStatus()
      if (!enable) {
        result = 2
      } else if (status === 0) {
        result = null
      } else if (status === 3 || status === 4) {
        result = 1
      } else {
        result = 0
      }
      plus.ios.deleteObject(cllocationManger)
      return result
    },
    // 判断相册权限是否开启
    iosPhotoAuth() {
      let result = 0
      const PHPhotoLibrary = plus.ios.importClass('PHPhotoLibrary')
      const authStatus = PHPhotoLibrary.authorizationStatus()
      console.log('authStatus:' + authStatus)
      if (authStatus === 3) {
        result = 1
        console.log('相册权限已经开启')
      } else {
        console.log('相册权限没有开启')
      }
      plus.ios.deleteObject(PHPhotoLibrary)
      return result
    },
    // 判断相机权限是否开启
    iosCameraAuth() {
      let result = 0
      const AVCaptureDevice = plus.ios.importClass('AVCaptureDevice')
      const authStatus = AVCaptureDevice.authorizationStatusForMediaType('vide')
      console.log('authStatus:' + authStatus)
      if (authStatus === 3) {
        result = 1
        console.log('相机权限已经开启')
      } else {
        console.log('相机权限没有开启')
      }
      plus.ios.deleteObject(AVCaptureDevice)
      return result
    },
    nativeObjView(permissionID: string | number) {
      const systemInfo = uni.getSystemInfoSync()
      const statusBarHeight = systemInfo.statusBarHeight
      const navigationBarHeight = systemInfo.platform === 'android' ? 48 : 44 // Set the navigation bar height based on the platform
      const totalHeight = statusBarHeight + navigationBarHeight
      let view = new plus.nativeObj.View('per-modal', {
        top: '0px',
        left: '0px',
        width: '100%',
        backgroundColor: '#444',
        // opacity: .5;
      })
      view.drawRect(
        {
          color: '#fff',
          radius: '5px',
        },
        {
          top: totalHeight + 'px',
          left: '5%',
          width: '90%',
          height: '100px',
        },
      )
      view.drawText(
        this.PERMISSION_MAP[permissionID].title,
        {
          top: totalHeight + 5 + 'px',
          left: '8%',
          height: '30px',
        },
        {
          align: 'left',
          color: '#000',
        },
        // @ts-expect-error: 存在的
        {
          onClick: (e) => {},
        },
      )
      view.drawText(
        this.PERMISSION_MAP[permissionID].desc,
        {
          top: totalHeight + 35 + 'px',
          height: '60px',
          left: '8%',
          width: '84%',
        },
        {
          whiteSpace: 'normal',
          size: '14px',
          align: 'left',
          color: '#656563',
        },
      )

      function show() {
        // @ts-expect-error: 存在的
        view = plus.nativeObj.View.getViewById('per-modal')
        view.show()
        view = null // 展示的时候也得清空，不然影响下次的关闭，不知道为啥
      }

      function close() {
        // @ts-expect-error: 存在的
        view = plus.nativeObj.View.getViewById('per-modal')
        view.close()
        view = null
      }
      return {
        show,
        close,
      }
    },
  },
})
